package com.pan.service.impl;

import com.pan.dao.freight.FreightDao;
import com.pan.dao.freight.FreightSelectDao;
import com.pan.dao.order1.OrderTable1SelectDao;
import com.pan.dao.order2.OrderTable2SelectDao;
import com.pan.entity.Freight;
import com.pan.entity.OrderTable1;
import com.pan.entity.OrderTable2;
import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import com.pan.excep.error.ServiceException;
import com.pan.feign.StockFeign;
import com.pan.service.FreightService;
import com.pan.tools.ConvertObject;
import com.pan.vo.FreightCreateVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("freightService")
public class FreightServiceImpl implements FreightService {

    @Resource
    private OrderTable2SelectDao orderTable2SelectDao;

    @Resource
    private OrderTable1SelectDao orderTable1SelectDao;

    @Resource
    private StockFeign stockFeign;

    @Resource
    private FreightDao freightDao;

    @Resource
    private FreightSelectDao freightSelectDao;


    @Override
    public Result<List<Freight>> selectList(List<Long> idList){
        List<Freight> list = freightDao.selectList(idList);
        Result<List<Freight>> result = new Result<>(ResultEnum.SUCCESS);
        result.setData(list);
        return result;
    }

    @Override
    public Result<Freight> selectById(Long id){
        Freight freight = freightSelectDao.selectById(id);
        Result<Freight> result = new Result(ResultEnum.SUCCESS)
                .setData(freight);
        return result;
    }

    @Override
    public Result createFreight(String adminTicket, FreightCreateVo freightCreateVo){
        Long order2Id = freightCreateVo.getOrder2Id();
        OrderTable2 orderTable2 = orderTable2SelectDao.selectById(order2Id);
        if (orderTable2 == null) {
            return new Result<>(ResultEnum.NOT_FOUND_ERROR);
        }
        OrderTable1 orderTable1 = orderTable1SelectDao.selectById(orderTable2.getPid());

        Freight freight = ConvertObject.convertObject(new Freight(),freightCreateVo)
                .setCompany("运输公司")
                .setUserId( orderTable1.getUserId())
                .setEndAddress(orderTable1.getAddress())
                .setFreightStatus(0);
        Long stockId = freightCreateVo.getStockId();
        Integer reduceCount = orderTable2.getGoodsCount();

        Result reduceResult = stockFeign.reduceGoodsCountNoCookie(adminTicket,stockId, Long.valueOf(reduceCount));
        if (reduceResult.getCode()!= 200){
            throw new ServiceException(403,"库存错误");
        }
        freightDao.insert(freight);
        Result result = new Result<>(ResultEnum.SUCCESS);
        return result ;
    }




}
